﻿using System;
using System.Windows.Controls.Primitives;
using System.Windows;

namespace Eniux.Windows.Controls.Core.Core
{
    public class ResizeThumb : Thumb
    {
        public ResizeThumb()
        {
            DragDelta += new DragDeltaEventHandler(this.ResizeThumb_DragDelta);

        }
        private void ResizeThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            Window designerItem = this.DataContext as Window;

            if (designerItem != null)
            {
                double deltaVertical, deltaHorizontal;

                switch (VerticalAlignment)
                {
                    case VerticalAlignment.Bottom:
                        deltaVertical = Math.Min(-e.VerticalChange, designerItem.ActualHeight - designerItem.MinHeight);
                        if (designerItem.Height - deltaVertical >= 0)
                            designerItem.Height -= deltaVertical;
                        break;
                    case VerticalAlignment.Top:
                        if (designerItem.Height - e.VerticalChange >= designerItem.MinHeight)
                        {
                            designerItem.Height -= e.VerticalChange;
                            designerItem.Top += e.VerticalChange;
                            designerItem.RenderTransform = null;
                        }
                        break;
                    default:
                        break;
                }

                switch (HorizontalAlignment)
                {
                    case HorizontalAlignment.Left:
                        if (designerItem.Width - e.HorizontalChange >= designerItem.MinWidth)
                        {
                            designerItem.Width -= e.HorizontalChange;
                            designerItem.Left += e.HorizontalChange;
                        }
                        break;
                    case HorizontalAlignment.Right:
                        deltaHorizontal = Math.Min(-e.HorizontalChange, designerItem.ActualWidth - designerItem.MinWidth);
                        if (designerItem.Width - deltaHorizontal >= 0)
                            designerItem.Width -= deltaHorizontal;
                        break;
                    default:
                        break;
                }
            }

            e.Handled = true;
        }
    }
}
